package com.luoxin.servicemap.remote;

import com.alibaba.fastjson.JSONObject;
import com.luoxin.internalcommon.constant.AmapConfigConstants;
import com.luoxin.internalcommon.dto.ResponseResult;
import com.luoxin.internalcommon.response.ServiceResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Slf4j
@Service
public class ServiceClient {
    @Value("${amap.key}")
    private String mapKey;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult add(String name) {
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.SERVICE_ADD_URL);
        url.append("?");
        url.append("key="+mapKey);
        url.append("&");
        url.append("name="+name);

        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        String body = forEntity.getBody();
        log.info("高德地图创建服务结果:{}", body);
        JSONObject result = JSONObject.parseObject(body);
        String errcode = result.getString("errcode");
        if (!"10000".equals(errcode)){
            String errmsg = result.getString("errmsg");
            return ResponseResult.fail(Integer.valueOf(errcode), errmsg);
        }
        JSONObject data = result.getJSONObject("data");
        String sid = data.getString("sid");
        ServiceResponse serviceResponse = new ServiceResponse();
        serviceResponse.setSid(sid);
        return ResponseResult.success(serviceResponse);
    }
}
